package com.elai.web.controller.baseconfig;

import com.elai.baseconfig.domain.BaseLesseeInfo;
import com.elai.baseconfig.service.IBaseLesseeInfoService;
import com.elai.common.annotation.Log;
import com.elai.common.core.controller.BaseController;
import com.elai.common.core.domain.AjaxResult;
import com.elai.common.core.domain.entity.SysUser;
import com.elai.common.core.page.TableDataInfo;
import com.elai.common.enums.BusinessType;
import com.elai.common.utils.DateUtils;
import com.elai.common.utils.SecurityUtils;
import com.elai.common.utils.StringUtils;
import com.elai.common.utils.poi.ExcelUtil;
import com.elai.baseconfig.domain.BaseApplicationInfoDO;
import com.elai.baseconfig.service.BaseApplicationInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 应用管理Controller
 *
 * @author elai
 * @date 2021-07-03
 */
@RestController
@RequestMapping("/config/application")
public class BaseApplicationInfoController extends BaseController
{
    @Autowired
    private BaseApplicationInfoService baseApplicationInfoService;

    @Autowired
    private IBaseLesseeInfoService baseLesseeInfoService;
    /**
     * 查询应用管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BaseApplicationInfoDO baseApplicationInfo)
    {
        startPage();
        SysUser sysUser=SecurityUtils.getLoginUser().getUser();
        if(!sysUser.isAdmin()){
            String lessionId=sysUser.getLesseeId();
            baseApplicationInfo.setLesseeId(lessionId);
        }
        List<BaseApplicationInfoDO> list = baseApplicationInfoService.selectBaseApplicationInfoList(baseApplicationInfo);
        return getDataTable(list);
    }

    /**
     * 导出应用管理列表
     */
    @PreAuthorize("@ss.hasPermi('config:application:export')")
    @Log(title = "应用管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BaseApplicationInfoDO baseApplicationInfo)
    {
        startPage();
        SysUser sysUser=SecurityUtils.getLoginUser().getUser();
        if(!sysUser.isAdmin()){
            String lessionId=sysUser.getLesseeId();
            baseApplicationInfo.setLesseeId(lessionId);
        }
        List<BaseApplicationInfoDO> list = baseApplicationInfoService.selectBaseApplicationInfoList(baseApplicationInfo);
        ExcelUtil<BaseApplicationInfoDO> util = new ExcelUtil<BaseApplicationInfoDO>(BaseApplicationInfoDO.class);
        return util.exportExcel(list, "application");
    }

    /**
     * 获取应用管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('config:application:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(baseApplicationInfoService.selectBaseApplicationInfoById(id));
    }

    /**
     * 新增应用管理
     */
    @PreAuthorize("@ss.hasPermi('config:application:add')")
    @Log(title = "应用管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BaseApplicationInfoDO baseApplicationInfo)
    {
        String appCode=baseApplicationInfo.getAppCode();
        BaseApplicationInfoDO b=new BaseApplicationInfoDO();
        b.setAppCode(appCode);
        List<BaseApplicationInfoDO> list = baseApplicationInfoService.selectBaseApplicationInfoList(b);
        if(list.size()>0){
            return AjaxResult.error("APPKey["+appCode+"]"+"已经存在，不允许重复添加");
        }
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(StringUtils.isNotEmpty(currentUser.getLesseeId())){
            BaseLesseeInfo lesseeInfo= baseLesseeInfoService.selectBaseLesseeInfoByLesseeId(currentUser.getLesseeId());
            if(lesseeInfo==null){
                return AjaxResult.error("添加应用'" + baseApplicationInfo.getName() + "'失败，租户ID不存在");
            }
            if("02".equals(lesseeInfo.getStatus())){
                return AjaxResult.error("添加应用'" +baseApplicationInfo.getName() + "'失败，租户异常请联系管理员");
            }
            if(lesseeInfo.getBeginDate().getTime()> DateUtils.getNowDate().getTime() || DateUtils.getNowDate().getTime()>lesseeInfo.getEndDate().getTime()){
                return AjaxResult.error("添加应用'" + baseApplicationInfo.getName() + "'失败，租户不在有效期内，请联系管理员");
            }
            baseApplicationInfo.setLesseeId(currentUser.getLesseeId());
            BaseApplicationInfoDO param=new BaseApplicationInfoDO();
            param.setLesseeId(currentUser.getLesseeId());
            List<BaseApplicationInfoDO> apps = baseApplicationInfoService.selectBaseApplicationInfoList(param);
            if(apps.size()>lesseeInfo.getLimitAppNum()){
                return AjaxResult.error("添加应用'" + baseApplicationInfo.getName() + "'失败，应用数量超出限制，只能添加"+lesseeInfo.getLimitAppNum()+"个应用");
            }
        }else{
            return AjaxResult.error("添加应用'" + baseApplicationInfo.getName() + "'失败，请联系管理员配置租户");
        }
        return toAjax(baseApplicationInfoService.insertBaseApplicationInfo(baseApplicationInfo));
    }

    /**
     * 修改应用管理
     */
    @PreAuthorize("@ss.hasPermi('config:application:edit')")
    @Log(title = "应用管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BaseApplicationInfoDO baseApplicationInfo)
    {
        return toAjax(baseApplicationInfoService.updateBaseApplicationInfo(baseApplicationInfo));
    }

    /**
     * 删除应用管理
     */
    @PreAuthorize("@ss.hasPermi('config:application:remove')")
    @Log(title = "应用管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(baseApplicationInfoService.deleteBaseApplicationInfoByIds(ids));
    }
}
